package com.ht.api.call.func.impl.transfer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.ht.api.bean.AjaxResult;
import com.ht.api.bean.LoginBean;
import com.ht.api.call.func.IFunctionCall;
import com.ht.api.db.Db;
import com.ht.api.db.DbList;
import com.ht.api.db.Entity;
import com.ht.api.db.StreamLoadConfig;
import com.ht.api.db.exception.HtException;
import com.ht.api.db.util.HtUtil;
import com.ht.api.open.OpenUtil;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 新增客户群接替
 * @author asq
 * @createTime 2025年3月9日 09:11:00
 */
@Slf4j
public class TransferChatAddFunctionCall implements IFunctionCall {
	/** 接口ID：分配在职成员的客户群 */
	private static final long API_ID_ON = 1899986491904495616L;
	/** 接口ID：分配离职成员的客户群 */
	private static final long API_ID_OFF = 1899991486251012096L;
	
	@Override
	public String getName() {
		return "新增客户群接替";
	}

	@Override
	public JSONObject execute(LoginBean me, JSONObject param, AjaxResult result) {
		// 验证参数
		HtUtil.checkParam(param, "appid", "new_owner", "chat_list");
		String appId = param.getStr("appid");
		String newOwner = param.getStr("new_owner");
		JSONArray chatList = param.getJSONArray("chat_list");
		
		// 验证群列表的参数
		if (chatList.isEmpty()) {
			throw new HtException("至少需要1个群~");
		}
		JSONObject chat0 = chatList.getJSONObject(0);
		HtUtil.checkParam(chat0, "chat_id", "owner_status", "owner");
		
		// 将所有群分为两组，群主在职的一组，离职的一组
	    Map<String, List<JSONObject>> chatGroup = chatList.stream()
    		.map(chat -> (JSONObject)chat).collect(Collectors.groupingBy(chat -> {
				return chat.getInt("owner_status") == 0 ? "on" : "off";
			}));
	    
	    // 调用企微接口:分配在职成员的客户群
	    List<JSONObject> onList = chatGroup.get("on");
	    if (onList != null && !onList.isEmpty()) {
	    	log.info("[TransferChatAddFunctionCall]分配在职成员的群，总数：{}", onList.size());
	    	transferChatList(me.getStreamLoadConfig(), appId, API_ID_ON, onList, newOwner, 0);
	    }
	    
	    // 调用企微接口:分配离职成员的客户群
	    List<JSONObject> offList = chatGroup.get("off");
	    if (offList != null && !offList.isEmpty()) {
	    	log.info("[TransferChatAddFunctionCall]分配离职成员的群，总数：{}", offList.size());
	    	transferChatList(me.getStreamLoadConfig(), appId, API_ID_OFF, offList, newOwner, 1);
	    }
		
		return JSONUtil.createObj();
	}
	
	/**
	 * 调用企微接口分配客户群
	 * @param streamConfig
	 * @param appId 应用ID
	 * @param apiid 接口ID
	 * @param chatList 群列表
	 * @param newOwner 新群主ID
	 * @param type 继承类型
	 */
	private void transferChatList(StreamLoadConfig streamConfig, String appId, long apiid, 
			List<JSONObject> chatList, String newOwner, int type) {
		// 调用企微接口
		JSONObject param = JSONUtil.createObj();
		param.set("chat_id_list", chatList.stream().map(chat -> chat.getStr("chat_id")).toList());
		param.set("new_owner", newOwner);
    	String str = OpenUtil.call(appId, apiid, param);
    	
    	// 接口调用成功后，保存本地数据
		DbList list = DbList.create();
		List<JSONObject> failedChatList = new ArrayList<>();
    	JSONObject obj = JSONUtil.parseObj(str);
		if (obj.getInt("errcode") == 0) {
			JSONArray failedChatArr = obj.getJSONArray("failed_chat_list");
			failedChatList = failedChatArr.stream().map(o -> (JSONObject)o).toList();
		}

		// 遍历本次继承的群，保存数据
		for (JSONObject chat : chatList) {
			String chatId = chat.getStr("chat_id");
			int parentErrcode = obj.getInt("errcode");
			boolean isFail = parentErrcode != 0 || failedChatList.stream().anyMatch(o -> o.getStr("chat_id").equals(chatId));
			int errcode = 0;
			if (isFail) {
				if (parentErrcode != 0) {
					errcode = parentErrcode;
				} else {
					errcode = getErrcode(chatId, failedChatList);
				}
			}
			
			Entity transferChat = Entity.create("wx_transfer_chat");
			transferChat.set("appid", appId);
			transferChat.set("new_owner", newOwner);
			transferChat.set("chat_id", chatId);
			transferChat.set("errcode", errcode);
			transferChat.set("type", type);
			transferChat.set("old_owner", chat.getStr("owner"));
			transferChat.set("status", isFail ? 2 : 1);
			list.add(transferChat);
		}
		
		Db.insertBatchWithStream(streamConfig, list);
	}
	
	/**
	 * 获取企微返回的errcode
	 * @param chatId 群ID
	 * @param failedChatList 企微返回的结果列表
	 * @return
	 */
	private int getErrcode(String chatId, List<JSONObject> failedChatList) {
		return failedChatList.stream().filter(o -> o.getStr("chat_id").equals(chatId))
				.map(o -> o.getInt("errcode")).findFirst().orElseGet(null);
	}
}
